/*************************************************************************
 * File Name:    Remove_Nth_Node_From_End_of_List.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/9 20:00:49
 * 
 * Description:  
 |-----------------------------------------------------------------------
 | Problem: Remove Nth Node From End of List
 |
 | Given a linked list, remove the nth node from the end of list and return its head.
 |
 | For example,
 |
 | Given linked list: 1->2->3->4->5, and n = 2.
 |
 | After removing the second node from the end, the linked list becomes 1->2->3->5.
 |
 | Note: Given n will always be valid.
 | Try to do this in one pass.
 |-----------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n)
    {
        if (head == NULL) return NULL;
        
        ListNode *tail, *p;
        
        p = NULL;
        for (tail = head->next; tail != NULL; tail = tail->next) {
            if (--n <= 0) {
                if (p == NULL) p = head;
                else p = p->next;
            }
        }
        
        ListNode *t;
        if (p == NULL) {
            t = head->next;
            delete head;
            return t;
        }
        
        t= p->next;
        p->next = p->next->next;
        delete t;
        
        return head;
    }
};

